<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="入库单号" prop="no">
            <el-input disabled v-model="formData.no" placeholder="保存时自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库时间" prop="inTime">
            <el-date-picker
              v-model="formData.inTime"
              type="date"
              value-format="x"
              placeholder="选择入库时间"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件" prop="fileUrl">
            <UploadFile :is-show-tip="false" v-model="formData.fileUrl" :limit="1" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              v-model="formData.supplierId"
              clearable
              filterable
              placeholder="请选择供应商"
              class="!w-1/1"
              :filter-method="handleSupplierFilterMethod"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="验收标准" prop="criteria">
            <el-input
              type="textarea"
              v-model="formData.criteria"
              :rows="1"
              placeholder="请输入验收标准"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <ContentWrap>
      <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
        <el-tab-pane label="入库产品清单" name="item">
          <StockInItemForm ref="itemFormRef" :items="formData.items" :disabled="disabled" />
        </el-tab-pane>
      </el-tabs>
    </ContentWrap>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { StockInApi, StockInVO } from '@/api/acm/stock/backIn'
import StockInItemForm from './components/StockInItemForm.vue'
import { SupplierApi, SupplierVO } from '@/api/erp/purchase/supplier'
import { ElMessage } from 'element-plus'

/** ERP 其它入库单 表单 */
defineOptions({ name: 'StockInForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
// 优化类型定义，明确表单数据结构
const formData = ref<Partial<StockInVO & { items: any[] }>>({
  id: undefined,
  supplierId: undefined,
  inTime: undefined,
  remark: undefined,
  criteria: undefined,
  fileUrl: '',
  items: [],
  no: undefined // 入库单号（后端生成，禁用状态）
})
// 完善表单校验规则，补充供应商必填校验
const formRules = reactive({
  inTime: [{ required: true, message: '入库时间不能为空', trigger: 'change' }], // 改为change触发，适配日期选择器
  supplierId: [{ required: true, message: '供应商不能为空', trigger: 'change' }], // 补充供应商必填校验，改为change触发
  remark: [{ max: 500, message: '备注不能超过500个字符', trigger: 'blur' }],
  criteria: [{ max: 500, message: '验收标准不能超过500个字符', trigger: 'blur' }]
})
const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref

// -------------------------- 核心修改：供应商下拉框回显问题修复 --------------------------
const supplierList = ref<SupplierVO[]>([]) // 下拉显示用供应商列表
const supplierAllList = ref<SupplierVO[]>([]) // 完整供应商列表（缓存所有数据）

/** 1. 加载完整供应商列表（仅加载一次，避免重复请求） */
const loadAllSuppliers = async () => {
  if (supplierAllList.value.length > 0) return supplierAllList.value // 已加载则直接返回
  try {
    const data = await SupplierApi.getSupplierSimpleList()
    supplierAllList.value = data || []
    return data
  } catch (error) {
    ElMessage.error('加载供应商列表失败，请重试')
    supplierAllList.value = []
    return []
  }
}

/** 2. 确保已选供应商在下拉列表中（回显补全逻辑） */
const ensureSelectedSupplierInList = async () => {
  await loadAllSuppliers()
  const selectedSupplierId = formData.value.supplierId
  if (selectedSupplierId) {
    // 检查已选供应商是否在显示列表中
    const isExist = supplierList.value.some((item) => item.id === selectedSupplierId)
    if (!isExist) {
      // 从完整列表中找到对应供应商并添加到显示列表
      const targetSupplier = supplierAllList.value.find((item) => item.id === selectedSupplierId)
      if (targetSupplier) supplierList.value.push(targetSupplier)
    }
  }
}

/** 3. 优化供应商过滤方法：合并已选数据与过滤结果 */
const handleSupplierFilterMethod = async (query?: string) => {
  await loadAllSuppliers() // 确保完整列表已加载

  // 步骤1：提取已选供应商（避免回显数据丢失）
  const selectedSuppliers: SupplierVO[] = []
  const selectedSupplierId = formData.value.supplierId
  if (selectedSupplierId) {
    const targetSupplier = supplierAllList.value.find((item) => item.id === selectedSupplierId)
    if (targetSupplier) selectedSuppliers.push(targetSupplier)
  }

  // 步骤2：根据查询条件过滤数据（保持首屏200条性能优化）
  let filteredSuppliers: SupplierVO[] = []
  if (!query) {
    // 无查询时：取完整列表前200条
    filteredSuppliers = [...supplierAllList.value].slice(0, 200)
  } else {
    // 有查询时：按供应商名称模糊匹配（不区分大小写）
    filteredSuppliers = supplierAllList.value.filter((supplier) =>
      supplier.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 步骤3：合并并去重（避免下拉列表出现重复选项）
  supplierList.value = Array.from(
    new Map([...selectedSuppliers, ...filteredSuppliers].map((item) => [item.id, item])).values()
  )
  return supplierList.value
}
// -----------------------------------------------------------------------------------

/** 子表的表单（原有逻辑保留） */
const subTabsName = ref('item')
const itemFormRef = ref()

/** 打开弹窗（修改：加载完整数据并补全回显） */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 先加载完整供应商列表，再初始化下拉显示列表
  await Promise.all([loadAllSuppliers(), handleSupplierFilterMethod()])

  // 修改/详情场景：加载入库单数据并补全供应商回显
  if (id) {
    formLoading.value = true
    try {
      const stockInData = await StockInApi.getStockIn(id)
      formData.value = { ...stockInData }
      // 确保子表数据初始化（避免空数组导致子表异常）
      formData.value.items = stockInData.items || []
      // 关键：补全已选供应商到下拉列表
      await ensureSelectedSupplierInList()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单（原有逻辑保留，优化数据格式） */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验主表和子表表单
  await formRef.value.validate()
  if (itemFormRef.value && typeof itemFormRef.value.validate === 'function') {
    await itemFormRef.value.validate()
  }

  // 提交请求
  formLoading.value = true
  try {
    const submitData = formData.value as unknown as StockInVO
    // 确保子表数据存在（避免后端接收空值）
    submitData.items = submitData.items || []

    if (formType.value === 'create') {
      await StockInApi.createStockIn(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await StockInApi.updateStockIn(submitData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success') // 通知父组件刷新数据
  } finally {
    formLoading.value = false
  }
}

/** 重置表单（原有逻辑保留，优化初始化） */
const resetForm = () => {
  formData.value = {
    id: undefined,
    supplierId: undefined,
    inTime: undefined,
    remark: undefined,
    criteria: undefined,
    fileUrl: '',
    items: [],
    no: undefined
  }
  formRef.value?.resetFields()
  // 重置子表（若子表提供reset方法）
  if (itemFormRef.value && typeof itemFormRef.value.reset === 'function') {
    itemFormRef.value.reset()
  }
}
</script>